﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using GBFinance.Web.Models;
using HiLand.Framework.BusinessCore;
using HiLand.Framework.BusinessCore.BLL;
using HiLand.Framework4.Permission.Attributes;
using HiLand.General;
using HiLand.General.BLL;
using HiLand.General.Entity;
using HiLand.Utility.Data;
using HiLand.Utility.Enums;
using HiLand.Utility.Paging;
using HiLand.Utility.Web;
using HiLand.Utility4.MVC.Data;
using Webdiyer.WebControls.Mvc;

namespace GBFinance.Web.Areas.Broker.Controllers
{
    [UserAuthorize(UserTypes.Broker)]
    public class BrokerBaseLoanController : Controller
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="loanType"></param>
        /// <param name="id"></param>
        /// <param name="viewName"></param>
        /// <returns></returns>
        public ActionResult LoanList(LoanTypes loanType, int id = 1, string viewName = "")
        {
            int pageIndex = id;
            int pageSize = Miscs.PageSizeManage;
            int startIndex = (pageIndex - 1) * pageSize + 1;
            string whereClause = string.Format(" LoanType= {0} AND LoanStatus!={1} AND GE.BrokerKey='{2}' ",
                (int)loanType, (int)LoanStatuses.UserUnCompleted, BusinessUserBLL.CurrentUser.UserGuid);
            string orderClause = "LoanID DESC";

            string queryDateBegin = RequestHelper.GetValue("queryDateBegin");
            string queryDateEnd = RequestHelper.GetValue("queryDateEnd");

            if (string.IsNullOrWhiteSpace(queryDateBegin) == false)
            {
                DateTime tempBegin = Converter.TryToDateTime(queryDateBegin,DateTimeHelper.Min,DateFormats.DMY);
                if (tempBegin != DateTime.MinValue)
                {
                    whereClause += string.Format(" AND LoanDate>='{0}' ", tempBegin);
                }
            }

            if (string.IsNullOrWhiteSpace(queryDateEnd) == false)
            {
                DateTime tempEnd = Converter.TryToDateTime(queryDateEnd, DateTimeHelper.Min, DateFormats.DMY);
                if (tempEnd != DateTime.MinValue)
                {
                    whereClause += string.Format(" AND LoanDate<='{0}' ", tempEnd.AddDays(1));
                }
            }

            string queryCondition = GetQueryCondition();
            if (string.IsNullOrWhiteSpace(queryCondition) == false)
            {
                whereClause += " AND " + queryCondition;
            }

            PagedEntityCollection<LoanBasicEntity> entityList = LoanBasicBLL.Instance.GetPagedCollection(startIndex, pageSize, whereClause, orderClause);
            List<LoanBasicExtEntity> tempList = new List<LoanBasicExtEntity>();
            foreach (var currentItem in entityList.Records)
            {
                LoanBasicExtEntity extEntity = Converter.InheritedEntityConvert<LoanBasicEntity, LoanBasicExtEntity>(currentItem);
                if (currentItem.LoanUserID != Guid.Empty)
                {
                    EnterpriseExtEntity currentLoanEnterprise = Converter.InheritedEntityConvert<EnterpriseEntity, EnterpriseExtEntity>(EnterpriseBLL.Instance.Get(currentItem.LoanUserID));
                    if (currentLoanEnterprise != null)
                    {
                        extEntity.EnterpriseFlowUpHistory = currentLoanEnterprise.FlowUpHistory;
                        extEntity.EnterpriseIndexID = currentLoanEnterprise.EnterpriseID;
                        extEntity.EnterpriseNote = currentLoanEnterprise.Note;

                        List<BusinessUser> applicants = BusinessUserBLL.GetUsersByDepartment(currentLoanEnterprise.EnterpriseGuid);
                        if (applicants != null && applicants.Count > 0)
                        {
                            BusinessUser mainApplicant = applicants[0];
                            extEntity.MainApplicant = string.Format("{0} {1}", mainApplicant.UserNameFirst, mainApplicant.UserNameLast);
                            extEntity.Email = mainApplicant.UserEmail;
                        }
                    }
                }
                tempList.Add(extEntity);
            }

            PagedList<LoanBasicExtEntity> pagedExList = new PagedList<LoanBasicExtEntity>(tempList, entityList.PageIndex, entityList.PageSize, entityList.TotalCount);

            if (viewName == "")
            {
                viewName = "LoanList";
            }

            string queryName = RequestHelper.GetValue("queryConditionName");
            string queryValue = RequestHelper.GetValue("queryConditionValue");
            this.PassParam("queryName", queryName);
            this.PassParam("queryValue", queryValue);

            this.PassParam("queryDateBegin", queryDateBegin);
            this.PassParam("queryDateEnd", queryDateEnd);

            return View(viewName, pagedExList);
        }


        #region 辅助方法
        /// <summary>
        /// 获取用户输入的查询条件
        /// </summary>
        /// <returns></returns>
        private string GetQueryCondition()
        {
            string result = string.Empty;
            string queryName = RequestHelper.GetValue("queryConditionName");
            string queryValue = RequestHelper.GetValue("queryConditionValue");

            switch (queryName)
            {
                case "CustomerNo":
                    if (string.IsNullOrWhiteSpace(queryValue) == false)
                    {
                        int customNo = Converter.TryToInt32(queryValue, 0);
                        if (customNo != 0)
                        {
                            result = string.Format(" EnterpriseID={0} ", customNo);
                        }
                    }
                    break;
                case "MainApplicant":
                    if (string.IsNullOrWhiteSpace(queryValue) == false)
                    {
                        result = string.Format(" ( UserNameFirst like '%{0}%'  OR  UserNameLast like '%{0}%'  ) ", SQLInjectionHelper.GetSafeSqlBeforeSave(queryValue));
                    }
                    break;
                case "Email":
                    if (string.IsNullOrWhiteSpace(queryValue) == false)
                    {
                        result = string.Format(" UserEmail like '%{0}%'  ", SQLInjectionHelper.GetSafeSqlBeforeSave(queryValue));
                    }
                    break;
                case "Approved":
                    result = string.Format(" LoanStatus={0} ", (int)LoanStatuses.Approved);
                    break;
                case "Rejected":
                    result = string.Format(" LoanStatus={0} ", (int)LoanStatuses.Rejected);
                    break;
                case "Deleted":
                    result = string.Format(" LoanStatus={0} ", (int)LoanStatuses.Deleted);
                    break;
                case "Collection":
                    result = string.Format(" LoanStatus={0} ", (int)LoanStatuses.Collection);
                    break;
                case "Blacklisted":
                    result = string.Format(" LoanStatus={0} ", (int)LoanStatuses.Blacklisted);
                    break;
                case "":
                default:
                    result = string.Empty;
                    break;
            }

            if (queryName != "Deleted")
            {
                if (string.IsNullOrWhiteSpace(result))
                {
                    result = " 1=1 ";
                }

                result += string.Format(" AND LoanStatus!={0}", (int)LoanStatuses.Deleted);
            }

            return result;
        }
        #endregion
    }
}
